package com.ly.algorithm.DataStructures.sparsearray;

/**
 * @Classname SparseArray
 * @Description TODO
 * @Date 2020/4/19 20:16
 * @Author 冷心影翼
 */
public class SparseArray {

    public static void main(String[] args) {
        //初始化二维矩阵
        int arr[][] = new int[11][11];
        arr[1][2] = 1;
        arr[2][3] = 2;
        for (int row[] : arr) {
            for(int it : row) {
                System.out.print(it+"\t");
            }
            System.out.println();
        }
        //统计非0元素
        int sum = 0;
        for (int row[] : arr) {
            for(int it : row) {
                if(it!=0) {
                    sum++;
                }
            }
        }
        System.out.println("sum="+sum);
        //初始化稀疏矩阵
        int sparseArr[][] = new int[sum+1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        //赋值
        int count = 0;
        for(int i=0;i<11;i++) {
            for(int j=0;j<11;j++) {
                if(arr[i][j]!=0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = arr[i][j];
                }
            }
        }
        //打印
        for(int i=0;i<sparseArr.length;i++) {
            System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
        }

        //稀疏矩阵->二维矩阵

        int arr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];

        for(int i=1;i<sparseArr.length;i++) {
            arr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        //打印
        for (int row[] : arr2) {
            for(int it : row) {
                System.out.print(it+"\t");
            }
            System.out.println();
        }
    }
}
